package com.singerw.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.singerw.annotations.ResponseResult;
import com.singerw.annotations.UserId;
import com.singerw.pojo.Share;
import com.singerw.service.ShareService;
import com.singerw.service.oss.OSSService;
import com.singerw.utils.OSSUtils;
import com.singerw.utils.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @version V1.0
 * @Package com.singerw.controller
 * @auhter 张欣
 * @date 2021/1/4-3:57 PM
 * @text <p>此处被 @UserId 注解的变量均为oss中的base地址,并非是 userId</p>
 */

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private OSSService ossService;

    @Autowired
    private ShareService shareService;

    /**
     * 获得文件列表
     *
     * @param jsonObject
     * @param userId
     * @return
     */
    @PostMapping("/list")
    @ResponseResult
    private String list(@RequestBody JSONObject jsonObject, @UserId String userId) {
        String path = userId + jsonObject.getString("path");
        return ossService.getFileList(path, false);
    }

    /**
     * 获得文件夹列表
     *
     * @param jsonObject
     * @param userId
     * @return
     */
    @PostMapping("/dir/list")
    @ResponseResult
    private String dirList(@RequestBody JSONObject jsonObject, @UserId String userId) {
        String path = userId + jsonObject.getString("path");
        return ossService.getFileList(path, true);
    }


    /**
     * 新建文件夹
     *
     * @param jsonObject
     * @param userId
     * @return
     */
    @PostMapping("/mkDir")
    @ResponseResult
    private String mkDir(@RequestBody JSONObject jsonObject, @UserId String userId) {
        String path = userId + jsonObject.getString("path");
        return ossService.mkDir(path, jsonObject.getString("dirName"));
    }

    /**
     * 文件上传
     *
     * @param path
     * @param file
     * @param userId
     * @return
     * @throws IOException
     * @todo 增加空间大小校验，完善返回内容。
     */
    @RequestMapping("/upload")
    @ResponseResult
    private String upload(@RequestParam("path") String path,
                          @RequestParam("file") MultipartFile file, @UserId String userId) throws IOException {
        path = userId + path + file.getOriginalFilename();
        System.out.println(path);
        ossService.putFile(path, file.getBytes());
        return "sucess";
    }

    @PostMapping("/delete")
    @ResponseResult
    private String delete(@RequestBody JSONObject jsonObject, @UserId String userId) {
        String path = jsonObject.getString("path");
        Boolean isRecycle = jsonObject.getBoolean("isRecycle");
        if(!isRecycle){
            ossService.deleteFile(userId + path, userId);
        }else{
            ossService.moveFile(userId,path,"user_recycle/" + OSSUtils.removeHead(userId)+ "/");
        }
        return "sucess";
    }

    @PostMapping("/rename")
    @ResponseResult
    private String rename(@RequestBody JSONObject jsonObject, @UserId String userId) {
        String path = jsonObject.getString("path");
        String name = jsonObject.getString("name");
        String newName = jsonObject.getString("newName");
        ossService.reNameFile(  userId,userId + path ,name, newName);
        return "sucess";

    }

    /**
     * 移动
     * todo 在移动文件夹的时候文件丢失
     *
     * @param jsonObject
     * @param userId
     * @return
     */
    @PostMapping("/move")
    @ResponseResult
    private String move(@RequestBody JSONObject jsonObject, @UserId String userId) {
        String path =  jsonObject.getString("path");
        String targetPath = jsonObject.get("target").toString();
        if(userId.indexOf("user_recycle/") != -1 || userId.indexOf("user_private/") != -1){
            targetPath = "user_space/" + OSSUtils.removeHead(userId) + "/";
        }else{
            targetPath = userId + targetPath;
        }
        ossService.moveFile(userId,  path, targetPath);

        return "sucess";
    }
    @PostMapping("/move/private")
    @ResponseResult
    public void movePrivate(@RequestBody JSONObject jsonObject, @UserId String userId){
        String path =  jsonObject.getString("path");
        String targetPath = "user_private/" + OSSUtils.removeHead(userId) + "/";
        ossService.moveFile(userId,  path, targetPath);
    }

    /**
     * 复制文件
     *
     * @param jsonObject
     * @param userId
     * @return
     */
    @PostMapping("/copy")
    @ResponseResult
    private String copy(@RequestBody JSONObject jsonObject, @UserId String userId) {
        String path = userId + jsonObject.getString("path");
        String targetPath = userId + jsonObject.get("target").toString();
        System.out.println(path);
        System.out.println(targetPath);
        ossService.copyFile(path, targetPath);
        return "sucess";
    }

    @PostMapping("/search")
    @ResponseResult
    private String search(@RequestBody JSONObject jsonObject, @UserId String userId) {
        String name = jsonObject.get("name").toString();
        return ossService.selectFile(userId, name);
    }

    @PostMapping("/format")
    @ResponseResult
    private String format(@RequestBody JSONObject jsonObject, @UserId String userId) {
        String format = jsonObject.get("format").toString();
        return ossService.getFileFormatList(userId + "/", format);

    }


    @GetMapping("download/{path}")
    @ResponseResult
    private String download(@PathVariable("path") String path, @UserId String userId, HttpServletRequest request, HttpServletResponse response) throws IOException {

        BASE64Decoder decoder = new BASE64Decoder();
        String pathing = userId + new String(URLDecoder.decode(new String(decoder.decodeBuffer(path)), "utf-8"));
        if (pathing.charAt(pathing.length() - 1) == '/') {
            ossService.zipFilesDown(request, response, OSSUtils.getDirName(path), pathing);
        } else {
            ossService.download(pathing, response);
        }
        return "success";
    }


    @GetMapping("share/download/{key}/{pwd}")
    private String ShareDownload(@PathVariable("key") String key,@PathVariable("pwd") String pwd, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String shareData = shareService.getShare(key, pwd);
        if (shareData.equals("0")) {
            return ResultUtils.fail("秘钥错误或文件已失效");
        }
        Share share = JSON.parseObject(shareData, Share.class);
        String fileName = share.getFileName();
        if (fileName.charAt(fileName.length() - 1) == '/') {
            ossService.zipFilesDown(request, response, OSSUtils.getDirName(share.getFileName()), share.getFilePath());
        } else {
            ossService.download(share.getFilePath(), response);
        }
        return "success";
    }

    @PostMapping("set/dir/permission")
    @ResponseResult
    private void setDirPermission(@RequestBody JSONObject jsonObject,@UserId String userId){
        String path = userId + jsonObject.getString("path");
        String name = OSSUtils.getDirName(path) + '/';
        String newName = OSSUtils.setDirPermission(name);
        ossService.reNameFile(userId,OSSUtils.removeName(path),name,newName);

    }
}



